package com.only4play.authcenter.v2.security.authentication.admin.password;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.only4play.authcenter.v2.security.model.PasswordLoginReq;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author hinzzz www.hinzzz.cn 157957329@qq.com
 * 2024-04-08
 */
public class AdminPasswordLoginProcessFilter extends AbstractAuthenticationProcessingFilter {

    protected AdminPasswordLoginProcessFilter(AuthenticationManager authenticationManager) {
        super("/admin/auth/passwordLogin", authenticationManager);
    }

    @Override
    public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException, IOException, ServletException {

        ObjectMapper objectMapper = new ObjectMapper();
        PasswordLoginReq passwordLoginReq = objectMapper.readValue(request.getInputStream(), PasswordLoginReq.class);
        AdminPasswordToken passwordToken = new AdminPasswordToken(passwordLoginReq.getUsername(), passwordLoginReq.getPassword());

        return this.getAuthenticationManager().authenticate(passwordToken);
    }
}
